//
//  ViewController.m
//  汽车之家
//
//  Created by mafeng on 16/8/9.
//  Copyright © 2016年 mafeng. All rights reserved.
//

#import "ViewController.h"
#import "Brand.h"
#import "List.h"
#import "Hothot.h"
#import "HotList.h"
#import "ExtentionList.h"
#import "ExtentionBrand.h"
#import "MyTableViewCell.h"
#import "HotTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "HotCollectionViewCell.h"
#import "ExtentionTableViewCell.h"
#import "ExtentionCollectionViewCell.h"
@interface ViewController ()<UITableViewDelegate, UITableViewDataSource, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong) NSMutableArray *brandArray;
@property (nonatomic, strong) NSMutableArray *listArray;
@property (nonatomic, strong) Hothot *hot;
@property (nonatomic, strong) ExtentionBrand *extentionBrand;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSDictionary *brandDict;

@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self handleBrandData];
    [self handleHotData];
    [self handleExtentionData];
    
}

 // 解析汽车品牌数据
- (void)handleBrandData {
    // 本⃣地⃣数⃣据⃣
//    NSString *path = [[NSBundle mainBundle] pathForResource:@"CarBrand" ofType:@"json"];
//    NSData *data = [NSData dataWithContentsOfFile:path];
//    NSError *error = nil;
//    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
    
    // 创⃣建⃣一⃣个⃣session
    NSURLSession *session = [NSURLSession sharedSession];
    // 从⃣网⃣络⃣获⃣取⃣数⃣据⃣
    NSURL *url = [NSURL URLWithString:@"http://app.api.autohome.com.cn/autov4.6/cars/brands-a2-pm2-v4.6.1-ts635580073583652962.html"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"GET";
    // session网⃣络⃣请⃣求⃣
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSError *rror = nil;
        self.brandDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&rror];
        NSDictionary *resultDict = _brandDict[@"result"];
        NSArray *array = resultDict[@"brandlist"];
        
        // 初始化数组
        self.brandArray = [NSMutableArray array];
        for (NSDictionary *dic in array) {
            NSArray *sameLetterArray = dic[@"list"];
            NSLog(@"%@", sameLetterArray);
            // 给model赋值
            Brand *brand = [[Brand alloc] initWithDictionary:dic];
            NSLog(@"####%@", brand);
            [self.brandArray addObject:brand];
        }
        NSLog(@"%@", _brandArray);
        // 插入数据, 插入主打车在第0位
        [_brandArray insertObject:[[Brand alloc] initWithDictionary:[NSDictionary dictionaryWithObjectsAndKeys:@"主", @"letter", nil]] atIndex:0];
        // 再次在第0位插入热门品牌
        [_brandArray insertObject:[[Brand alloc] initWithDictionary:[NSDictionary dictionaryWithObjectsAndKeys:@"热", @"letter", nil]] atIndex:0];
        // 将⃣界⃣面⃣的⃣加⃣载⃣放⃣到⃣
        dispatch_async(dispatch_get_main_queue(), ^{
             [_tableView reloadData];
        });
       
    }];
    [task resume];
}

 // 解析热门车型数据
- (void)handleHotData {
//    NSString *path = [[NSBundle mainBundle] pathForResource:@"HotBrand" ofType:@"json"];
//    NSData *data = [NSData dataWithContentsOfFile:path];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURL *url = [NSURL URLWithString:@"http://cars.app.autohome.com.cn/dealer_v6.0.0/dealer/hotbrands-pm1.json"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
   // request.HTTPMethod = @"GET";
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSError *erro = nil;
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&erro];
        NSDictionary *ResultDict = dict[@"result"];
        self.hot = [[Hothot alloc] initWithDictionary:ResultDict];
    }];
    [task resume];
}

// 解析主打车数据
- (void)handleExtentionData {
//    NSString *path = [[NSBundle mainBundle] pathForResource:@"Extention" ofType:@"json"];
//    NSData *data = [NSData dataWithContentsOfFile:path];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURL *url = [NSURL URLWithString:@"http://adnewnc.app.autohome.com.cn/autov5.7.0/ad/infoad.ashx?appid=2&platform=1&version=6.2.0&networkid=0&adtype=1&provinceid=110000&lng=121.550888&lat=38.889660&pageindex=1&deviceid=d1ecb940123d620cb05a1b2b0a00da8bdd5e4fbe&idfa=981CD0F4-F1F0-4D0F-9C5E-58280F40E4B0&devicebrand=apple&devicemodel=iPhone&gps_city=210200&pageid=d1ecb940123d620cb05a1b2b0a00da8bdd5e4fbe1470913307169&isretry=0"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"GET";
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSError *erro = nil;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:&erro];
        NSDictionary *dict = dic[@"result"];
        NSLog(@"🐂🐂%@", dict);
        self.extentionBrand = [[ExtentionBrand alloc] initWithDictionary:dict];
        // 将⃣界⃣面⃣的⃣重⃣新⃣加⃣载⃣
        dispatch_async(dispatch_get_main_queue(), ^{
            [_tableView reloadData];
        });
    }];
    [task resume];
}

// tableview的协议方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    NSLog(@"%ld", _brandArray.count);
    return _brandArray.count;
}

// 返回每个setion的row的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }
    if (section == 1) {
        return 1;
    }
    return [_brandArray[section] list].count;
}

// 返回每个cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        return 200;
    }
    if (indexPath.section == 1) {
        return 150;
    }
  
        return 78;
  
    
}



 // 返回cell的协议方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        HotTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"hotReuse"];
        cell.backgroundColor = [UIColor yellowColor];
        return cell;
    } else if (indexPath.section == 1) {
        ExtentionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ExtentionTableViewCellReuse"];
        return cell;
    } else {
    MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    List *list = [_brandArray[indexPath.section] list][indexPath.row];
    cell.myLabel.text = list.name;
    [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:list.imgurl]];
    return cell;
    }
}

 // 返回区头的标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return [_brandArray[section] letter];
}


// 返回索引的协议方法
- (nullable NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    NSMutableArray *array = [NSMutableArray array];
    for (Brand *brand in _brandArray) {
        [array addObject:brand.letter];
    }
    return array;
}

// collection协议方法
// 返回每个section的item的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSLog(@"%f", collectionView.superview.bounds.size.height);
    if (collectionView.superview.bounds.size.height == 199.5) {
            return 10;
    }
    if (collectionView.superview.bounds.size.height == 149.5) {
        return 3;
    }
    return 0;
}

// 返回每个item的样式
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if ((collectionView.superview.bounds.size.height == 199.5)) {
        HotCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"hotCollectionViewCellReuse" forIndexPath:indexPath];
        [cell.imageView sd_setImageWithURL:[NSURL URLWithString:[_hot.list[indexPath.row] img]]];
        cell.label.text = [_hot.list[indexPath.row] name];
        return cell;
    }
    if (collectionView.superview.bounds.size.height == 149.5) {
        ExtentionCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"extentionCollectionViewCellReuse" forIndexPath:indexPath];
        [cell.imageView sd_setImageWithURL:[NSURL URLWithString:[_extentionBrand.list[indexPath.row] img]]];
        cell.label.text = [_extentionBrand.list[indexPath.row] seriesname];
        return cell;
    }
    return nil;
}

// 返回item的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView.superview.bounds.size.height == 199.5) {
        return CGSizeMake(CGRectGetWidth(collectionView.bounds) / 5, CGRectGetHeight(collectionView.bounds) / 2);
    }
    if (collectionView.superview.bounds.size.height == 149.5) {
         return CGSizeMake(CGRectGetWidth(collectionView.bounds) / 3, CGRectGetHeight(collectionView.bounds));
    }
    return CGSizeZero;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
